<?php

/** @package codymvc */

/**
 * @class CommandFactory
 * @brief Maps the request URI to the name of a Command to run.
 */

class CommandFactory {

    static function create($uri) {
        $command_class = self::get_command_class($uri);
		$command = new $command_class();
		return $command;
    }

    /** 
     * Determines the name of the command class to use for a given request URI. Uses the
     * first 'segment' of the URI, eg. /foo/bar/baz the first segment is 'foo'.
     * If the first character of the segment is numeric, eg. /404, prepends
     * an underscore. This is because PHP cannot have classnames with a numeric
     * first character.
     * The first letter is capitalised.
     * If the URL is '' or '/', uses the class set as config option 'default_command'.
     * @param $uri (String) The request URI.
     * @return (String) The Command class to use for the given URI.
     * @todo Make it use a View if the Command isn't found and there's no default command
     */
    static private function get_command_class($uri) {
		$request = parse_url($uri);
        $segments = explode('/',preg_replace('~/+~', '/', $request['path']));   
        $command_class = CodyMVC::get_config('default_command');
        if ( count($segments) >= 2 ) {
            $command_class = $segments[1];
        }
        // Prepend underscore if the first character is a digit
        if ( is_numeric( substr($command_class,0,1) ) ) {
            $command_class = '_'.$command_class;
        }
	    $command_class = ucfirst(str_replace('-','_',strtolower($command_class)));
        if ( $command_class == '' ) {
            $command_class = CodyMVC::get_config('default_command');
        }
	    if ( ! class_exists($command_class) ) {
			$command_class = CodyMVC::get_config('not_found_command');
        }
        return $command_class;
    }

}

?>
